<template>
	<view class="customerOrders">
		<view v-if="showEmpty">
			<view class="my-orders-index-empty">暂无订单</view>
		</view>

		<view class="" :key="data.id" v-for="data in orderList " :item="data">
			<view class="orderDate">
				预订日期：{{data.ymd}} {{data.weekDay}}
			</view>

			<view class="five">

				<view @tap="navigateTo('/pages/OrderDetailsPage/OrderDetailsPage?orderNo='+data.orderNo)">
					<view class="content1 content">
						<view class="left">{{data.orderDetail}}</view>
						<view class="right">¥{{data.orderAmount / 100}}</view>
					</view>
					<view class="content2 content">
						<view class="left">{{data.orderType}}</view>
						<view class="right">{{data.orderStatusText}}</view>
					</view>
				</view>
				<view class="content3 content">
					<view v-if="data.orderStatus === 1" class="right1 right" @tap="cancelOrder(data.id)">取消订单
					</view>
					<view v-if="data.orderStatus === 1" class="right2 right" @tap="onPay(data)">付款
					</view>
					<view v-if="data.orderStatus === 3" class="right1 right" @tap="refundOrder(data)">退款</view>
					<view v-if="[2,9,10].includes(data.orderStatus)" class="right1 right"
						@tap="deleteOrder(data.id)">删除订单</view>
					<view class="right2 right" v-if="data.orderStatus != 1"  @tap="reOrder(data)">再次预定
					</view>
				</view>
			</view>
		</view>

	</view>
</template>

<script lang="js">
	import {
		navigateTo,
		getProvider,
		showModal,
		showToast,
		uniLogin
	} from "../../utils/promise"
	import showModelFn from "../../utils/showModel";
	import {
		getOrderList,
		deleteOrder,
		refundOrder,
		againPayOrder,
		cancelOrder,
		syncOrder
	} from '../../api/room';
	import getWeekDay from '../../utils/weekDay';
	import spliceMMDD from '../../utils/stringSpliceMMDD';

	export default {
		name: "AllOrders",
		data() {
			return {
				orderList: [],
				orderStatus: [
					'未知',
					'待付款',
					'支付失败',
					'等待入住',
					'已入住',
					'未知',
					'已评论',
					'未知',
					'未知',
					'交易已取消',
					'已退款',
					'退款中'
				], //0-未知，1-待付款，2-支付失败，3-支付成功, 等待入住，4-已入住，5-未知，6=已评论，9=已删除（交易已取消），10=已退款，11=退款中
				showEmpty: false
			};
		},
		mounted() {
			//刷新订单列表
			this.getOrderList()
		},
		methods: {
			navigateTo,
			navTo(e) {
				// console.log(e)
				navigateTo({
					url: e.currentTarget.dataset.url
				})
			},
			delOrder() {
				// e.predefault()
				showModelFn(() => {

				})
			},
			getOrderList() {
				let params = {
					//'orderStatus': 1,
					'current': 1,
					'size': 1000
				}
				getOrderList(params).then((res) => {
					if (res.code === 200) {
						console.log('res--orderlist')
						console.log(res)
						const {
							data
						} = res
						this.orderList = data.records
						this.orderList.forEach((f) => {
							let date1 = new Date(f.bookingCheckInDate.substring(0, 10));
							let date2 = new Date(f.bookingCheckOutDate.substring(0, 10));
							let diffMilliseconds = date2 - date1; // 差值毫秒数
							let diffDays = diffMilliseconds / (1000 * 60 * 60 * 24); // 转换为天数
							console.log(spliceMMDD(f.bookingCheckInDate.substring(0, 10), 'MM'))
							f.orderDetail = spliceMMDD(f.bookingCheckInDate.substring(0, 10), 'MM') + '月' +
								spliceMMDD(f
									.bookingCheckInDate.substring(0, 10), 'DD') + '日(入住)-' + spliceMMDD(f
									.bookingCheckOutDate.substring(0, 10), 'MM') + '月' + spliceMMDD(f
									.bookingCheckOutDate.substring(0, 10), 'DD') + '日(离店)' + diffDays +
								'晚/' + f
								.roomQuantity + '间';
							f.orderType = f.categoryName;
							f.orderAmount = f.totalPrice;
							f.orderStatusText = this.orderStatus[f.orderStatus]

							f.weekDay = getWeekDay(f.createTime)
							f.ymd = f.createTime.substring(0, 4) + '年' + f.createTime.substring(5, 7) +
								'月' + f.createTime.substring(8, 10) + '日'

						});
						this.showEmpty = this.orderList.length === 0
						console.log(this.orderList)
					}
				}).catch((err) => {
					console.log(err)
				})

				//this.orderList = [{"orderDetail":"住宿+滕王阁+庐山，2 天 1 晚","orderType":"豪华套间","orderAmount":"3683"},{"orderDetail":"住宿+滕王阁，3 天 2 晚","orderType":"豪华套间","orderAmount":"3853"},{"orderDetail":"住宿+庐山，5 天 4 晚","orderType":"豪华套间3","orderAmount":"388"}]
			},
			deleteOrder(orderId) {
				console.log("deleteOrder--begin--" + orderId)
				showModal({
					title: "删除确认",
					content: "是否确认删除",
					showCancel: true,
					cancelText: "否",
					confitmText: "是"
				}).then((res) => {
					if (res.cancel) {
						console.log("return。。")
						return
					}
					//调用后台删除订单接口，传参orderId
					console.log("deleteOrder--deal--" + orderId)
					let params = {
						'id': orderId
					}
					console.log("deleteOrder--deal-params.id-" + params.id)
					deleteOrder(params).then((res) => {
						if (res.code == 200) {
							//刷新下订单列表
							this.getOrderList()
							console.log("。。delete--done")
						}
					}).catch((err) => {
						console.log(err)
					})
				}).catch((err) => {
					console.log(err)
				})
			},
			cancelOrder(orderId) {
				console.log("deleteOrder--begin--" + orderId)
				showModal({
					title: "取消确认",
					content: "取消订单后无法恢复", // ，优惠券将原路返还
					showCancel: true,
					cancelText: "否",
					confitmText: "是"
				}).then((res) => {
					if (res.cancel) {
						return
					}
					//调用后台删除订单接口，传参orderId
					console.log("cancelOrder--deal--" + orderId)
					cancelOrder(orderId).then((res) => {
						if (res.code == 200) {
							//刷新下订单列表
							this.getOrderList()
							console.log("。。delete--done")
						}
					}).catch((err) => {
						console.log(err)
					})
				}).catch((err) => {
					console.log(err)
				})
			},
			async refundOrder(data) {
				// 只考虑微信支付
				let that = this;
				uni.showModal({
					title: "是否确认退款",
					confirmText: "确认",
					success: async function(res) {
						if (res.confirm) {
							uni.showLoading();
							let params = {
								orderNo: data.orderNo
							};
							let result = await refundOrder(params);
							if (result.code === 200) {
								uni.showToast({
									icon: "none",
									title: "已经申请退款",
									duration: 2000,
									complete: () => {
										setTimeout(() => {
											uni.hideLoading();
											that.getOrderList();
										}, 2000);
									},
								});
							} else {
								uni.showToast({
									icon: "none",
									title: result.msg,
									duration: 2000,
									complete: () => {
										uni.hideLoading();
									},
								});
							}
						} else if (res.cancel) {
							// 用户取消
						}
					},
				});
			},
			async onPay(data) {
				let that = this;
				let orderNo = data.orderNo
				let res = await againPayOrder({
					orderNo: orderNo
				});
				if (res.code === 200 && res.data !== null) {
					wx.requestPayment({
						timeStamp: res.data.timeStamp, //时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间
						nonceStr: res.data.nonceStr, //随机字符串，长度为32个字符以下。
						package: res.data.packageDate, //统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=*
						signType: res.data.signType, //签名类型，默认为MD5，支持HMAC-SHA256和MD5。注意此处需与统一下单的签名类型一致
						paySign: res.data.paySign, //密钥
						success: (res) => {
							uni.hideLoading()
							uni.showToast({
								title: "支付成功",
								icon: "none",
							});
							syncOrder(orderNo).then((res1) => {
                setTimeout(() => that.getOrderList(), 500)
							}).catch((err) => {
                setTimeout(() => that.getOrderList(), 2000)
              })
						},
						fail: (err) => {
							uni.hideLoading()
							uni.showToast({
								title: "支付失败",
								icon: "none",
							});
						},
					});
				} else {
					uni.showToast({
						icon: "none",
						title: res.msg,
					});
				}
			},
			reOrder(orderData) {
				const params = {
					guestName: orderData.guestName,
					guestMobile: orderData.guestMobile,
					userRemark: orderData.userRemark || '',
					adultsQuantity: orderData.adultsQuantity,
					childQuantity: orderData.childQuantity,
					roomQuantity: orderData.roomQuantity,
					categoryId: orderData.categoryId,
					categoryName: orderData.categoryName,
					isReOrder: true // 标记是再次预定
				}
				navigateTo({
					url: `/pages/ReservationConfirmationPage/ReservationConfirmationPage?order=${JSON.stringify(params)}`
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	@import "../../static/commonStyleLess/grayBox.less";

	.my-orders-index-empty {
		width: 100%;
		text-align: center;
		display: flex;
		justify-content: center;
		padding-top: 200rpx;
		font-size: 28rpx;
	}

	.customerOrders {
		// 公共样式部分
		font-family: 'PingFang SC';
		letter-spacing: -0.82rpx;
		font-weight: 400;
		letter-spacing: 0px;

		.orderDate {
			font-weight: 400;
			font-size: 24rpx;
			color: #979797;
			margin-top: 20rpx;
			margin-bottom: 16rpx;
			margin-left: 30rpx;
			background-color: #FFFFFF;
			padding: 10rpx 30rpx;
			border-radius: 30rpx;
			width: 55%;
		}

		.orderTable {
			width: 690rpx;
			border-radius: 16rpx;
			background: #FFFFFF;
			margin: 0 auto;
			padding: 28rpx 30rpx;

			.ot_top {
				font-weight: 600;
				font-size: 28rpx;
				letter-spacing: 0px;

				.ott_left {

					color: #222222;
				}

				.ott_right {
					color: #FF4D00;

				}

			}

			.ot_middle {

				font-size: 26rpx;
				letter-spacing: 0px;
				color: #979797;
				margin-top: 40rpx;

			}

			.ot_bottom {
				display: flex;
				justify-content: flex-end;
				margin-top: 40rpx;
				align-items: center;


				.otb_two {

					width: 160rpx;
					height: 56rpx;
					border-radius: 8rpx;
					border-width: 1rpx;
					text-align: center;
					line-height: 56rpx;

				}

				.otb_one {
					font-size: 26rpx;
					color: #979797;
					border: 1 rpx solid #979797;
				}

				.otb_two {
					background: #0F4C97;
					color: #FFFFFF;
					margin-left: 20rpx;

				}
			}
		}

	}

	.five {
		// width: 690rpx;
		// height: 270rpx;
		margin: 20rpx 30rpx;
		border-radius: 16rpx;
		background: #FFFFFF;
		display: flex;
		flex-direction: column;
		justify-content: center;
		padding: 30rpx;
		box-sizing: border-box;

		.content {
			display: flex;
			justify-content: space-between;
			width: 100%;
		}

		.content1 {
			font-family: 'PingFang SC';
			font-weight: 600;
			font-size: 28rpx;
			letter-spacing: 0px;

			.left {
				// width: 476rpx;
				// height: 40rpx;
				// line-height: 40rpx;
				color: #222222;
				font-size: 28rpx;
			}

			.right {
				// width: 68rpx;
				// height: 40rpx;
				// line-height: 40rpx;
				color: #FF4D00;
			}
		}

		.content2 {
			margin-top: 40rpx;
			color: #979797;
			font-family: 'PingFang SC';

			.left {
				// width: 182rpx;
				// height: 36rpx;
				font-weight: 400;
				font-size: 26rpx;
				// line-height: 36rpx;
				letter-spacing: 0px;
			}

			.right {
				// width: 130rpx;
				// height: 36rpx;
				font-weight: 400;
				font-size: 26rpx;
				// line-height: 36rpx;
				letter-spacing: 0px;
				color: #FF4D00;
			}
		}

		.content3 {
			margin-top: 40rpx;
			justify-content: flex-end;

			.right {
				width: 160rpx;
				height: 56rpx;
				line-height: 56rpx;
				border-radius: 8rpx;
				border-width: 1rpx;
				text-align: center;
				font-family: 'PingFang SC';
				font-weight: 400;
				font-size: 26rpx;
				line-height: 56rpx;
				letter-spacing: 0px;
				margin-left: 20rpx;
			}

			.right1 {
				border: 1rpx solid #979797;
				color: #979797;
			}

			.right2 {
				background: #0F4C97;
				color: #FFFFFF;
			}
		}
	}
</style>
